/**
 * 
 */
package com.ctg.payroll2.util.xlsImport;

import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.DateFormulaCell;

/**
 * @author
 * 
 */
public final class CellUtils {
	public static Object getCellValue(HeadMapping hm, Cell cell)
			throws NumberFormatException {
		if (null == hm || null == hm.getType()) {
			return cell.getContents();
		}

		String type = hm.getType();
		String defaultValue = hm.getDefaultValue();

		if (type.equals("java.lang.String")) {
			if (!cell.getContents().equals("")) {
				return cell.getContents();
			} else {
				if (hm.getDefaultValue() != null) {
					return hm.getDefaultValue();
				}
			}
			return "";
		}

		if (type.equals("byte") || type.equals("java.lang.Byte")) {
			try {
				return Byte.parseByte(cell.getContents());
			} catch (NumberFormatException nfe) {
				if (defaultValue != null) {
					return Byte.parseByte(defaultValue);
				}
				throw new NumberFormatException();
			}
		}

		if (type.equals("short") || type.equals("java.lang.Short")) {
			try {
				return Short.parseShort(cell.getContents());
			} catch (NumberFormatException nfe) {
				if (defaultValue != null) {
					return Short.parseShort(defaultValue);
				}
				throw new NumberFormatException();
			}
		}

		if (type.equals("int") || type.equals("java.lang.Integer")) {
			try {
				return Integer.parseInt(cell.getContents());
			} catch (NumberFormatException nfe) {
				if (defaultValue != null) {
					return Integer.parseInt(defaultValue);
				}
				throw new NumberFormatException();
			}
		}

		if (type.equals("long") || type.equals("java.lang.Long")) {
			try {
				return Long.parseLong(cell.getContents());
			} catch (NumberFormatException nfe) {
				if (defaultValue != null) {
					return Long.parseLong(defaultValue);
				}
				throw new NumberFormatException();
			}
		}

		if (type.equals("double") || type.equals("java.lang.Double")) {
			try {
				return Double.parseDouble(cell.getContents());
			} catch (NumberFormatException nfe) {
				if (defaultValue != null) {
					return Double.parseDouble(defaultValue);
				}
				throw new NumberFormatException();
			}
		}

		if (type.equals("float") || type.equals("java.lang.Float")) {
			try {
				return Float.parseFloat(cell.getContents());
			} catch (NumberFormatException nfe) {
				if (defaultValue != null) {
					return Float.parseFloat(defaultValue);
				}
				throw new NumberFormatException();
			}
		}

		if (type.equals("java.util.Date")) {
			if (cell.getType() == CellType.DATE
					|| cell.getType() == CellType.DATE_FORMULA) {
				return ((DateCell) cell).getDate();
			} else {
				throw new NumberFormatException();
			}
		}

		throw new NumberFormatException();
	}
}
